package org.jeecg.modules.friends.pics;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import org.apache.commons.compress.utils.Lists;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.oss.OssBootUtil;
import org.jeecg.modules.friends.model.UserPicsDO;
import org.jeecg.modules.friends.service.UserPicsService;
import org.jeecg.modules.friends.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Maps;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author cold
 * @data 2024/5/16 21:44
 * @version 1.0
 */
@Slf4j
@Api(tags="上传相关接口")
@RestController
@RequestMapping("/friends/pic")
@Scope("prototype")
public class PicsController {


    private static final long MAX_IMAGE_SIZE = 10 * 1024 * 1024;
    private static final ExecutorService FILE_UPLOAD_THREAD =
            Executors.newFixedThreadPool(10);
    private static String endPoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";

    @Autowired
    private UserPicsService userPicsService;

    @ResponseBody
    @PostMapping("/uploadPics")
    @ApiOperation("上传图片文件，使用multipart方式")
    //@RequiresRoles("admin")
    public Result upload(@RequestParam("file") MultipartFile multipartFile) {
        Result result = new Result();
        if (multipartFile.getSize() > MAX_IMAGE_SIZE) {
            return new Result().error500("图片大小不能超过10M");
        }
        try {
            Map<String, Object> getUploadResult = FileUploadUtils.getUploadResult(multipartFile, "/usr/share/nginx/html/img/images/",
                    "http://47.113.194.112/img/images/");
            result.setResult(getUploadResult);
            result.success("上传成功！");
        } catch (Exception ex) {
            log.info(ex.getMessage(), ex);
            result.error500("上传失败");
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/uploadOssPics")
    @ApiOperation("上传图片文件，使用multipart方式")
    //@RequiresRoles("admin")
    public Result uploadOss(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.getSize() > MAX_IMAGE_SIZE) {
            return new Result().error500("图片大小不能超过10M");
        }
        Result result = new Result();
        try {
            String url = OssBootUtil.upload(multipartFile, "images/" + UUID.randomUUID());
            Map<String, Object> resultMap = Maps.newHashMap();
            resultMap.put("success", true);
            resultMap.put("portrait_path", url);//将存储头像的项目路径返回给页面
            result.setResult(resultMap);
            result.success("上传成功！");
        } catch (Exception ex) {
            log.info(ex.getMessage(), ex);
            result.error500("上传失败");
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/batchUploadOssPics")
    @ApiOperation("批量上传图片")
    //@RequiresRoles("admin")
    public Result batchUploadOss(@RequestParam("files") MultipartFile[] multipartFile) {
        if (multipartFile.length > 5) {
            return new Result().error500("一次最多上传5张");
        }
        for (MultipartFile file : multipartFile) {
            if (file.getSize() > MAX_IMAGE_SIZE) {
                return new Result().error500("图片大小不能超过10M");
            }
        }
        List<Future<String>> futures = Lists.newArrayList();
        for (MultipartFile file : multipartFile) {
            Future<String> picUrl = FILE_UPLOAD_THREAD.submit(
                    () -> OssBootUtil.upload(file, "images/" + UUID.randomUUID()));
            futures.add(picUrl);
        }

        Result result = new Result();
        try {
            List<String> url = futures.stream().map(future -> {
                try {
                    return future.get();
                } catch (Exception e) {
                    log.error("uploadOss error", e);
                    return null;
                }
            }).collect(Collectors.toList());

            Map<String, Object> resultMap = Maps.newHashMap();
            resultMap.put("success", true);
            resultMap.put("portrait_path", url);//将存储头像的项目路径返回给页面
            result.setResult(resultMap);
            result.success("上传成功！");
        } catch (Exception ex) {
            log.info(ex.getMessage(), ex);
            result.error500("上传失败");
        }
        return result;
    }

    @ResponseBody
    @PostMapping("/washPics")
    @ApiOperation("批量上传图片")
    public Result washData() throws MalformedURLException {
        List<UserPicsDO> userPicsDOS = userPicsService.findByPage();
        for (UserPicsDO userPicsDO : userPicsDOS) {
            if (userPicsDO.getPicUrl().contains("internal")) {
               userPicsDO.setPicUrl(userPicsDO.getPicUrl().replace("oss-cn-hangzhou-internal", "oss-cn-hangzhou"));
               userPicsService.update(userPicsDO);
            }
        }
        return Result.OK();
    }
}